<template>
    <div class="app-container">
        <!-- 添加、批量删除按钮等标题栏 -->
        <div class="filter-container add1">
            <el-form style="">
                <el-form-item>
                    <!-- 按钮级别的控制,使用hasPerm来判断是否应该有添加这个按钮 -->
                    <el-button type="primary" icon="plus" @click="showCreate" v-if="hasPerm('article:add')">{{textMap.createTxt}}</el-button>
                    <el-button type="danger" v-if="multipleSelectionFlag" @click="delSelect">{{textMap.batchDeleteTxt}}</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 关键词状态、搜索栏 -->
        <div class="searchWord">
            <el-input v-model="search" placeholder="请输入搜索内容" @input="inputFunction()"></el-input>
        </div>
        <br>

        <!-- 列表显示栏 -->
        <el-table class="tabless" :data="list" v-loading.body="listLoading" element-loading-text="拼命加载中" border fit highlight-current-row 
        :row-class-name="tableRowClassName" @selection-change="handleSelectionChange">
                <!-- 复选框 -->
                <el-table-column type="selection" width="55" v-if="displayItem.select">
                </el-table-column>

                <el-table-column align="center" label="序号" width="80" v-if="displayItem.id">
                    <template slot-scope="scope">
                        <!-- 文章的索引，设置自增等序列 -->
                        <span v-text="getIndex(scope.$index)"> </span>
                    </template>
                </el-table-column>

                <el-table-column align="center" prop="keyword_level2" label="关键词" style="width: 60px;" v-if="displayItem.name"></el-table-column>
                <el-table-column align="center" prop="topic" label="所属领域" style="width: 60px;" v-if="displayItem.topic"></el-table-column>
                <el-table-column align="center" prop="keyword_level1" label="所属类别" style="width: 60px;" v-if="displayItem.name"></el-table-column>
                <el-table-column align="center" prop="create_time" label="创建时间" style="width: 60px;" v-if="displayItem.create_time"></el-table-column>
                <el-table-column align="center" prop="update_time" label="修改时间" style="width: 60px;" v-if="displayItem.update_time"></el-table-column>
                <el-table-column align="center" prop="mark" label="备注" style="width: 60px;" v-if="displayItem.mark"></el-table-column>
                
                <el-table-column align="center" label="管理" width="200" v-if="displayItem.manageMent">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="edit" @click="showUpdate(scope.$index)">{{textMap.updateTxt}}</el-button>
                        <el-button type="danger" @click="handleDelete(scope.$index, scope.row)">{{textMap.deleteTxt}}</el-button>
                    </template>
                </el-table-column>

        </el-table>
        
        <!-- 删除提示框 -->
        <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
            <div class="del-dialog-cnt">{{textMap.deleteDigTxt}}</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="delVisible = false">{{textMap.clearTxt}}</el-button>
                <el-button type="primary" @click="deleteRow" >{{textMap.okTxt}}</el-button>
            </span>
        </el-dialog>

        <!-- 批量删除提示框 -->
        <el-dialog title="提示" :visible.sync="delVisibleByBatch" width="300px" center>
            <div class="del-dialog-cnt">{{textMap.batchDeleteDigTxt}}</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="delVisibleByBatch = false">{{textMap.clearTxt}}</el-button>
                <el-button type="primary" @click="delAll" >{{textMap.okTxt}}</el-button>
            </span>
        </el-dialog>

        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form class="small-space" :model="tempKeyword" label-position="left" label-width="120px" style='width: 400px; margin-left:50px;'>
                <el-form-item :label="textMap['nameTxt']" required>
                    <el-input type="text" v-model="tempKeyword.keywordName" @keyup.native = "handlerKeyword"></el-input>
                    <el-tag type="danger" v-if="this.displayInfoFromBack">{{infoFromBack}}</el-tag>          
                </el-form-item>
                <el-form-item :label="textMap['topicTxt']" required v-if="dialogStatus=='createTxt' | dialogStatus=='updateTxt'">
                    <el-select v-model="tempKeyword.keywordTopicId" placeholder="请选择" v-show="false">
                        <el-option
                            v-for="item in topicList"
                            :key="item.id"
                            :label="item.topic"
                            :value="item.id">
                        </el-option>
                    </el-select>
                    <el-row class="demo-autocomplete" placeholder="请搜索并选择" v-if="dialogStatus=='createTxt' | dialogStatus=='updateTxt'" >
                        <el-col :span="30">
                            <el-autocomplete class="inline-input" v-model="tempKeyword.keywordTopic" :fetch-suggestions="querySearch1" @select="handleSelect1"></el-autocomplete>
                        </el-col>
                    </el-row>
                </el-form-item>
                    <el-form-item :label="textMap['areaTxt']" required v-if="dialogStatus=='createTxt' | dialogStatus=='updateTxt'">
                    <el-select v-model="tempKeyword.keywordAreaId" placeholder="请选择" v-show="false">
                        <el-option
                            v-for="item in areaList"
                            :key="item.id"
                            :label="item.area"
                            :value="item.id">
                        </el-option>
                    </el-select>
                    <el-row class="demo-autocomplete" placeholder="请搜索并选择" v-if="dialogStatus=='createTxt' | dialogStatus=='updateTxt'" >
                        <el-col :span="30">
                            <el-autocomplete class="inline-input" v-model="tempKeyword.keywordArea" :fetch-suggestions="querySearch2" @select="handleSelect2"></el-autocomplete>
                        </el-col>
                    </el-row>
                </el-form-item>
                <el-form-item :label="textMap['markTxt']" required v-if="dialogStatus=='createTxt' | dialogStatus=='updateTxt'">
                    <el-input type="textarea" v-model="tempKeyword.keywordMark"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">{{textMap.clearTxt}}</el-button>
                <el-button v-if="dialogStatus=='createTxt'" type="primary" @click="createKeyword" :disabled="disableCreate">{{textMap.addTxt}}</el-button>
                <el-button type="primary" v-if="dialogStatus=='updateTxt'" @click="updateKeyword">{{textMap.updateTxt}}</el-button>    
            </div>
        </el-dialog>

        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="listQuery.pageNum" 
            :page-size="listQuery.pageRow"
            :total="totalCount"
            :page-sizes="[3,10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            class="pagination">
        </el-pagination>
    </div>

</template>

<script>
export default {
    data() {
        return {
            totalCount: 0, //分页组件--数据总条数
            list: [],//表格的数据
            listLoading: false,//数据加载等待动画

            //弹出框的相关配置
            dialogStatus: 'createTxt',
            dialogFormVisible: false,

            //翻页功能的相关配置
            listQuery: {
                pageNum: 1,//页码
                pageRow: 10,//每页条数
                name: ''
            },

            textMap: {
                deleteTxt: '删 除',
                batchDeleteTxt: '批量删除',
                updateTxt: '修 改',
                clearTxt: '取 消',
                okTxt: '确 定',
                addTxt: '创 建',
                createTxt: '添加关键词',
                nameTxt:'关键词名称',
                topicTxt:'所属领域',
                areaTxt:'所属类别',
                createTimeTxt:'创建时间',
                updateTimeTxt:'修改时间',
                markTxt:'备注',
                deleteDigTxt: '删除后数据不可恢复，是否确定删除？',
                batchDeleteDigTxt: '批量删除后数据不可恢复，是否确定批量删除？',
            },

            // 搜索框中的内容
            search:'',
            // 记录显示字段
            displayItem:{
                select:true,
                id:true,
                name:true,
                topic:true,
                create_time:true,
                update_time:true,
                mark:true,
                manageMent:true,
            },

            //该对象组织前端添加关键词信息，以POST请求形式传到后台
            tempKeyword: {
                keywordId: -1,
                keywordName: "",
                keywordTopic: "", 
                keywordTopicId: -1, 
                keywordAreaId: -1,
                keywordArea: "",  
                keywordMark: "",
            },

            //实时匹配输入数据，因为相同的关键词不能够重复输入（实时从后台返回来的数据)
            infoFromBack:'',
            displayInfoFromBack:false, //填写表单实时查重后提示
            disableCreate:false,

            //所有的主题领域，从数据库直接去除，用于下拉菜单
            topicList: [], 
            //实时搜索主题输入
            topicList2: [],
            areaList: [], 
            areaList2: [],
            //删除提示弹框的状态
            delVisible:false,
            //批量删除提示弹框的状态
            delVisibleByBatch:false,

            //批量删除存储的数据项列表
            multipleSelection:[],
            multipleSelectionFlag : true,
        }
    },
    created() {
        this.getList();
        this.getAllTopics();
        this.getAllArea();
    },
    methods: {
        getList() {
            //查询列表
            this.listLoading = true;
            this.api({
                url: "/keyword/listKeyword",
                method: "get",
                params: this.listQuery
                }).then(data => {
                    console.log(data)
                    this.listLoading = false;
                    this.list = data.list;
                    this.tables = data.list;
                    this.totalCount = data.totalCount;
                })
        },
        getListBySearch(val) {
            // console.log("val:"+val);
            //查询列表
            if (!this.hasPerm('article:list')) {
                return
            }
            this.listLoading = true;
            this.listQuery.value = val;
            // console.log(this.listQuery);
            this.api({
                url: "/keyword/listKeywordBySearch",
                method: "get",
                params: this.listQuery
            }).then(data => {
                // console.log(data)
                this.listLoading = false;
                this.list = data.list;
                this.totalCount = data.totalCount;
            })
        },
        //获取所有的主题列表
        getAllTopics() { 
            this.api({
            url: "/keyword/listTopic",
            method: "get"
            }).then(data => {
                console.log("listTopic:",data)
                this.topicList = data.list;
                //提供给实时搜索
                //console.log("data.length: ",data.list.length);
                for(var i = 0 ; i < data.list.length ; i++){
                    var temp = data.list[i];
                    temp['id_nickname'] = data.list[i]['topic'];
                    console.log('temp:', temp);
                    this.topicList2.push(temp);
                }
                var json = JSON.parse(JSON.stringify(data.list).replace(/id_nickname/g,"value"));
                this.topicList2 = json;
                console.log('topicList2:', this.topicList2);
            })
        },
        getAllArea() { 
            this.api({
            url: "/keyword/listArea",
            method: "get"
            }).then(data => {
                console.log("listArea:",data)
                this.areaList = data.list;
                //提供给实时搜索
                //console.log("data.length: ",data.list.length);
                for(var i = 0 ; i < data.list.length ; i++){
                    var temp = data.list[i];
                    temp['id_nickname'] = data.list[i]['area'];
                    console.log('temp:', temp);
                    this.areaList2.push(temp);
                }
                var json = JSON.parse(JSON.stringify(data.list).replace(/id_nickname/g,"value"));
                this.areaList2 = json;
                console.log('areaList2:', this.areaList2);
            })
        },
        handlerKeyword(){
            // return;
            console.log("keywordName:",this.tempKeyword.keywordName)
            this.api({
                url: "/keyword/getKeywordtByName",
                method: "get",
                params: this.tempKeyword.keywordName
            }).then(data => {
                console.log("data:",data);
                //存在该关键词，因此不可以重复插入
                if(data === "exist"){
                    this.displayInfoFromBack = true;
                    this.infoFromBack = "存在该关键词，不可重复添加";
                    this.disableCreate = true;
                }
                else{
                    this.displayInfoFromBack = false;
                    this.infoFromBack = "";
                    this.disableCreate = false;
                }
            })
        },
        createKeyword() { 
            //return;
            // console.log("keywordTopicId:",this.topicList2);
            // console.log("keywordTopicId:",this.tempKeyword.keywordTopicId);
            // if(this.tempKeyword.keywordTopicId == -1){
            //     this.tempKeyword.keywordTopicId = this.topicList2.length + 1;
            // }
            // console.log("keywordTopicId:",this.topicList.indexOf(this.tempKeyword.keywordTopicId-1).topic);
            // if(this.tempKeyword.keywordTopic != this.topicList.indexOf(this.tempKeyword.keywordTopicId-1).topic){
            //     this.tempKeyword.keywordTopicId = this.topicList2.length + 1;
            // }
            // console.log("data:",this.tempKeyword),
            this.api({
                url: "/keyword/addKeyword",
                method: "post",
                data: this.tempKeyword
            }).then(() => {
                let msg = "添加成功";
                this.dialogFormVisible = false;
                this.$message({
                    message: msg,
                    type: 'success',
                    duration: 1 * 1000,
                    onClose: () => {
                        this.getList();
                    }
                })
            })
        },
        updateKeyword() {
            this.api({
            url: "/keyword/updateKeyword",
            method: "post",
            data: this.tempKeyword
            }).then(() => {
                let msg = "修改成功";
                this.dialogFormVisible = false;
                this.$message({
                    message: msg,
                    type: 'success',
                    duration: 1 * 1000,
                    onClose: () => {
                        this.getList();
                    }
                })
            })
        },
        // 确定删除
        deleteRow(){
            let _vue = this;
            // 写自己的删除的对象
            // console.log(this.delarr)
            console.log("_vue.list:");
            console.log(_vue.list);
            console.log("_vue.index:"+_vue.idx);
            let rowItem = _vue.list[_vue.idx];
            //rowItem.deleteStatus = '2';
            console.log("rowItem:");
            console.log(rowItem);
            _vue.api({
                url: "/keyword/deleteKeyword",
                method: "post",
                data: rowItem
            }).then(() => {
                console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx")
                if(this.search == ""){
                    _vue.getList();
                }
                else{
                    // alert("我怎么就空了呢？")
                    _vue.getListBySearch(this.search);
                }
            }).catch(() => {
                _vue.$message.error("删除失败")
            })
            this.delVisible = false;//关闭删除提示模态框
        },
        delSelect(){
            const length = this.multipleSelection.length;
            if(length == 0){
                this.delWarnInfo();
            }else{
                this.delVisibleByBatch = true;//显示删除弹框
            }
        },
        // 当批量删除的时候,如果要是没有选中,弹出提醒
        delWarnInfo() {
            this.$message('请选择您要删除的数据');
        },
        //批量删除
        delAll() {
            var lengths = this.multipleSelection.length;
            
            for (let i = 0; i < lengths; i++) {
                console.log(this.multipleSelection[i]);
                this.api({
                    url: "/keyword/deleteKeyword",
                    method: "post",
                    data: this.multipleSelection[i]
                }).then(() => {
                    if(this.search == ""){
                        // alert("我不空啊")
                        this.getList();
                    }
                    else{
                        // alert("我怎么就空了呢？")
                        this.getListBySearch(this.search);
                    }
                }).catch(() => {
                    this.$message.error("删除失败")
                })
            }
            this.delVisibleByBatch = false;//关闭删除提示模态框
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log(this.multipleSelection);
        },
        showUpdate($index) {
            //显示修改对话框
            //绑定相应内容
            this.tempKeyword.keywordId = this.list[$index].id;
            this.tempKeyword.keywordName = this.list[$index].keyword_level2;
            this.tempKeyword.keywordTopic = this.list[$index].topic;
            this.tempKeyword.keywordTopicId = this.list[$index].topic_id;
            this.tempKeyword.keywordAreaId = this.list[$index].keyword_level1;
            this.tempKeyword.keywordArea = this.list[$index].keyword_level1;
            this.tempKeyword.keywordMark = this.list[$index].mark;

            this.dialogStatus = "updateTxt"
            this.dialogFormVisible = true

            this.infoFromBack = '';
            this.displayInfoFromBack = false;
            this.enableCreate = false
        },
        //实时搜索输入的内容
        querySearch1(queryString, cb) {
            var topicLists = this.topicList2;
            var results = queryString ? topicLists.filter(this.createFilter(queryString)) : topicLists;
            // 调用 callback 返回建议列表的数据
            console.log(results)
            cb(results);
        },
        querySearch2(queryString, cb) {
            var areaLists = this.areaList2;
            var results = queryString ? areaLists.filter(this.createFilter(queryString)) : areaLists;
            // 调用 callback 返回建议列表的数据
            console.log(results)
            cb(results);
        },
        //单行删除
        handleDelete(index, row) {
            console.log("index:"+index);
            console.log(row);
            this.idx = index;
            this.msg=row;//每一条数据的记录
            // this.delarr.push(this.msg.PackingId);//把单行删除的每条数据的id添加进放删除数据的数组
            this.delVisible = true;
        },
        handleSelect1(item) {
            this.tempKeyword.keywordTopicId = item.id;
        },
        handleSelect2(item) {
            this.tempKeyword.keywordAreaId = item.id;
        },
        getIndex($index) {
            //表格序号
            return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1
        },
        handleSizeChange(val) {
            //改变每页数量
            this.listQuery.pageRow = val
            this.handleFilter();
        },
        handleCurrentChange(val) {
            //改变页码
            this.listQuery.pageNum = val
            this.getList();
            
        },
        handleFilter() {
            //查询事件
            this.listQuery.pageNum = 1
            this.getList()
        },
        inputFunction(){
            console.log(this.search);
            console.log(this.search == "");
            if(this.search){
                this.getListBySearch(this.search);
            }
            if(this.search == ""){
                this.getList();
            }
        },
        showCreate() {
            //显示新增对话框
            this.tempKeyword.keywordName = "";
            this.tempKeyword.keywordTopic = "";
            this.tempKeyword.keywordArea = "";
            this.tempKeyword.keywordMark = "";
            this.dialogStatus = "createTxt";
            this.dialogFormVisible = true

            this.infoFromBack = '';
            this.displayInfoFromBack = false;
            this.enableCreate = false
        },
        createFilter(queryString) {
                return (staff) => {
                return (staff.value.toLowerCase().indexOf(queryString.toLowerCase()) >= 0);
            };
        },
        // generalFun(){
        //     if(this.search){
        //         if(this.listQuery.sortby == "" & this.listQuery.order == ""){
        //             this.getListBySearch(this.search);
        //         }
        //         else if(this.listQuery.sortby == "content" && this.listQuery.order == "ASC"){
        //             // alert("你好啊")
        //             // this.listQuery.sortby = this.prop;
        //             // this.listQuery.order = "ASC";
        //             this.getListByContentHaveSearch();
        //         }
        //         else if(this.listQuery.sortby == "content" && this.listQuery.order == "DESC"){
        //             // alert("很好啊")
        //             // this.listQuery.sortby = this.prop;
        //             // this.listQuery.order = "DESC";
        //             this.getListByContentHaveSearch();
        //         }
        //         else if(this.listQuery.sortby == "createTime" && this.listQuery.order == "ASC"){
        //             // this.listQuery.sortby = this.prop;
        //             // this.listQuery.order = "ASC";
        //             this.getListByOrderCreateTimeHaveSearch();
        //         }
        //         else if(this.listQuery.sortby == "createTime" && this.listQuery.order == "DESC"){
        //             // this.listQuery.sortby = this.prop;
        //             // this.listQuery.order = "DESC";
        //             this.getListByOrderCreateTimeHaveSearch();
        //         }
        //         else{
        //             // ...
        //         }
        //     }
        //     // 没有搜索内容，所以可以直接
        //     else{
        //     // alert("ssssssssssssssssss")
        //     // console.log(this.prop);
        //     // console.log(this.order);
        //         if(this.listQuery.sortby == "" & this.listQuery.order == ""){
                    
        //             this.getList();
        //         }
        //         else if(this.listQuery.sortby == "content" && this.listQuery.order == "ASC"){
        //             // this.listQuery.sortby = this.prop;
        //             // this.listQuery.order = "ASC";
        //             // ...
        //             this.getListByOrderContent();
        //         }
        //         else if(this.listQuery.sortby == "content" && this.listQuery.order == "DESC"){
        //             // this.listQuery.sortby = this.prop;
        //             // this.listQuery.order = "DESC";
        //             this.getListByOrderContent();
        //         }
        //         else if(this.listQuery.sortby == "createTime" && this.listQuery.order == "ASC"){
        //             // this.listQuery.sortby = this.prop;
        //             // this.listQuery.order = "ASC";
        //             this.getListByOrderCreateTime();
        //         }
        //         else if(this.listQuery.sortby == "createTime" && this.listQuery.order == "DESC"){
        //             // this.listQuery.sortby = this.prop;
        //             // this.listQuery.order = "DESC";
        //             this.getListByOrderCreateTime();
        //         }else{
        //             // ...
        //             this.getList();
        //             // alert("我是空的！")
        //         }
        //     }
        // },
    }
}
</script>

<style>
.el-table .warning-row {
    background:whitesmoke;
    
     /* background: #ffffff; */
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
  
  .pagination{
    background-color:lavender;
    margin-right: 0%;
    text-align: right;
  }

  .searchWord .add1{
    display: inline;
  }

</style>


